package cn.iocoder.yudao.module.iot.service.operationhistory;

import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.iot.controller.admin.operationhistory.vo.OperationHistoryPageReqVO;
import cn.iocoder.yudao.module.iot.controller.admin.operationhistory.vo.OperationHistorySaveReqVO;
import cn.iocoder.yudao.module.iot.dal.dataobject.operationhistory.OperationHistoryDO;
import cn.iocoder.yudao.module.iot.dal.mysql.operationhistory.OperationHistoryMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.iot.enums.ErrorCodeConstants.OPERATION_HISTORY_NOT_EXISTS;

/**
 * 操作历史记录 Service 实现类
 *
 * @author 云智节
 */
@Service
@Validated
public class OperationHistoryServiceImpl implements OperationHistoryService {

    @Resource
    private OperationHistoryMapper operationHistoryMapper;

    @Override
    public Long createOperationHistory(OperationHistorySaveReqVO createReqVO) {
        // 插入
        OperationHistoryDO operationHistory = BeanUtils.toBean(createReqVO, OperationHistoryDO.class);
        operationHistoryMapper.insert(operationHistory);

        // 返回
        return operationHistory.getId();
    }

    @Override
    public void updateOperationHistory(OperationHistorySaveReqVO updateReqVO) {
        // 校验存在
        validateOperationHistoryExists(updateReqVO.getId());
        // 更新
        OperationHistoryDO updateObj = BeanUtils.toBean(updateReqVO, OperationHistoryDO.class);
        operationHistoryMapper.updateById(updateObj);
    }

    @Override
    public void deleteOperationHistory(Long id) {
        // 校验存在
        validateOperationHistoryExists(id);
        // 删除
        operationHistoryMapper.deleteById(id);
    }

    @Override
        public void deleteOperationHistoryListByIds(List<Long> ids) {
        // 删除
        operationHistoryMapper.deleteByIds(ids);
        }

    private void validateOperationHistoryExists(Long id) {
        if (operationHistoryMapper.selectById(id) == null) {
            throw exception(OPERATION_HISTORY_NOT_EXISTS);
        }
    }

    @Override
    public OperationHistoryDO getOperationHistory(Long id) {
        return operationHistoryMapper.selectById(id);
    }

    @Override
    public PageResult<OperationHistoryDO> getOperationHistoryPage(OperationHistoryPageReqVO pageReqVO) {
        return operationHistoryMapper.selectPage(pageReqVO);
    }

    @Override
    public PageResult<OperationHistoryDO> getOperationHistoryPage(OperationHistoryPageReqVO pageReqVO, Long userId) {
        return operationHistoryMapper.selectPageByUserId(pageReqVO, userId);
    }

}